#pragma once

#include <gtl/script/script.h>

namespace gtl
{

namespace dui
{

template<class T>
class events
{
protected:
	typedef events<T> events_type;

protected:
	events()
	{
	}

protected:
	void create(gtl::xml& node)
	{
		gtl::xml* effect = node[_T("events")];
		if(effect == NULL)
			return;

		const gtl::xml::attribs_type& attribs = effect->attribs();
		for(size_t i = 0; i < attribs.size(); ++i)
		{
			gtl::tstr& event = m_events[attribs[i].first];
			event = attribs[i].second;
			if(!static_cast<T*>(this)->script_id().empty())
				event.replace(_T("this"), static_cast<T*>(this)->script_id());
			else
				event.replace(_T("this"), static_cast<T*>(this)->id());
		}
	}

	void dispatch_event(const gtl::tchar* event)
	{
		if(event == NULL)
			return;

		std::map<gtl::tstr, gtl::tstr>::iterator ite = m_events.find(event);
		if(ite == m_events.end())
			return;

		gtl::script* scrpt = NULL;
		static_cast<T*>(this)->visit(&visitor_get_script(scrpt));
		if(scrpt == NULL)
			return;

		scrpt->eval(gtl::str_warp((*ite).second));
	}

protected:
	std::map<gtl::tstr/*name*/, gtl::tstr/*script code*/> m_events;
};

} // end of namespace dui

} // end of namespace gtl